//
//  HACChartViewBase.m
//  Pods
//
//  Created by Hotacool on 2017/8/30.
//
//

#import "HACChartView.h"
#import "HACBasicComponents.h"

NSString *const HACBasicDataLabel = @"HACBasicDataLabel";
@interface HACChartView ()
@end

@implementation HACChartView {
    CGFloat _labelHeight;//坐标label字高
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    // 初始化页面属性
    self.backgroundColor = [UIColor clearColor];
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.xAxisCount = 5;
    self.yAxisCount = 5;
    _pointRect = CGRectZero;
    _axisXRenderer = [[HACAxisRenderer alloc] initWithDataProvider:self];
    _axisXRenderer.axisType = DrawingAxisTypeX;
    _axisYRenderer = [[HACAxisRenderer alloc] initWithDataProvider:self];
    _axisYRenderer.axisType = DrawingAxisTypeY;
    
    _leftAxis = [[HACAxisComponents alloc] init];
    _leftAxis.axisType = DrawingAxisTypeY;
    _leftAxis.labelCount = 5;
    _leftAxis.labelWidth = 40;
    _rightAxis = [[HACAxisComponents alloc] init];
    _rightAxis.axisType = DrawingAxisTypeY;
    _rightAxis.labelCount = 5;
}

- (void)setData:(HACChartData *)data {
    _data = data;
    [self calculateLimitValue];
}

- (void)addIncrementData:(HACChartData *)data {
    _data = [_data appendWithData:data];
    //TODO: recalculate limit values
}

- (void)refreshUI {
    [self calculateLimitValue];
    [self setNeedsDisplay];
}

- (void)clean {
    _data = nil;
    [self refreshUI];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    if (_visualCount > 0 && !CGRectEqualToRect(self.bounds, CGRectZero)) {
        [self updateFrame];
    }
}

- (void)setVisualCount:(NSInteger)visualCount {
    _visualCount = visualCount;
    if (visualCount > 0 && !CGRectEqualToRect(self.bounds, CGRectZero)) {
        [self updateFrame];
    }
}

- (void)updateFrame {
    self.pointRect = self.bounds;
    if (!self.leftAxis) {
        return;
    }
    //计算字高
    CGSize textSize = [@"0.0" sizeWithAttributes:@{NSFontAttributeName : self.leftAxis.textFont}];
    _labelHeight = textSize.height;
    if (self.leftAxis.labelPosition == HACAxisLabelPositionOutside) {
        self.singleWidth = FormatValueWithRemain((CGRectGetWidth(self.frame)-self.leftAxis.labelWidth) / (self.visualCount - 1), 3);
        self.pointRect = CGRectMake(self.leftAxis.labelWidth, self.bounds.origin.y + _labelHeight/2, self.bounds.size.width-self.leftAxis.labelWidth, self.bounds.size.height - _labelHeight);
    } else {
        self.singleWidth = FormatValueWithRemain(CGRectGetWidth(self.frame) / (self.visualCount - 1), 3);
    }
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.axisXRenderer drawInRect:rect context:context];
    [self.axisYRenderer drawInRect:rect context:context];
}

#pragma mark ----- calculate max/min value
// 计算最大，最小值
- (void)calculateLimitValue {
    CGFloat max = FLT_MIN;
    CGFloat min = FLT_MAX;
    self.maxValue = (max == FLT_MIN) ? .0 : max;
    self.minValue = (min == FLT_MAX) ? .0 : min;
}

#pragma mark -- provider protocol
- (NSArray *)X_axisDatasInRect:(CGRect)rect {
    return [self xAxisDatasInRect:rect];
}

- (NSArray *)Y_axisDatasInRect:(CGRect)rect {
    return [self yAxisDatasInRect:rect];
}

- (NSArray <HACAxisComponents *>*)xAxisDatasInRect:(CGRect)rect {
    NSInteger axisCount = self.leftAxis.labelCount;
    if (axisCount <= 0)
        return nil;
    
    NSMutableArray *xAxisDrawingData = [NSMutableArray array];
    // 从下往上
    for (int index = 0; index < axisCount; index++) {
        HACAxisComponents *axisItem = [[HACAxisComponents alloc] init];
        axisItem.index = index;
        axisItem.axisType = DrawingAxisTypeX;
        axisItem.queueLocation = CGQueueLocation(index, axisCount);
        CGFloat y = [self calculatorYForValue:index min:0 max:axisCount - 1 inRect:self.pointRect];
        [xAxisDrawingData addObject:axisItem];
        
        // x轴左边的默认值，按照最大值等分
        axisItem.text = [self stringForAxisTextItem:axisItem];
        if (!axisItem.text) // 如果没有返回使用默认值
        {
            CGFloat yValue = self.minValue + (ABS(self.maxValue - self.minValue) / (axisCount - 1)) * index;
            int digits = self.basicInfoData.priceDigits!=0?self.basicInfoData.priceDigits:0;
            //format
            if (self.leftAxis.customFormat) {
                @try {
                    axisItem.text = [NSString stringWithFormat:self.leftAxis.customFormat, yValue/pow(10, digits)];
                }
                @catch (NSException *exception) {
                    NSLog(@"Error: self.leftAxis.customFormat: %@", self.leftAxis.customFormat);
                }
            } else {
                axisItem.text = [NSString stringWithFormat:@"%.2f", yValue/pow(10, digits)];
            }
            axisItem.textFont = self.leftAxis.textFont;
            CGFloat midValue = self.minValue + (self.maxValue - self.minValue)/2;// openPrice
            if (self.leftAxis.customLabelColor) {
                axisItem.textColor = self.leftAxis.textColor;
            } else {
                if (yValue > midValue) {
                    axisItem.textColor = [self colorWithValueType:DrawingUpValue];;
                } else if (yValue < midValue) {
                    axisItem.textColor = [self colorWithValueType:DrawingDownValue];;
                } else {
                    axisItem.textColor = [self colorWithValueType:DrawingEqualValue];;
                }
            }
            yValue = (midValue>0)?ABS(yValue - midValue)/midValue*100:0;
            axisItem.extText = [NSString stringWithFormat:@"%.1f%%", yValue];
            axisItem.extTextColor = axisItem.textColor;
            axisItem.extTextFont = self.rightAxis.textFont;
        }
        
        CGSize textSize = [axisItem.text sizeWithAttributes:@{NSFontAttributeName : axisItem.textFont}];
        CGRect frame = CGRectMake(CGRectGetMinX(rect), y, textSize.width , textSize.height);
        if (self.leftAxis.labelPosition == HACAxisLabelPositionOutside) {
            frame = CGRectMake(self.pointRect.origin.x - textSize.width - 4, y-_labelHeight/2, textSize.width , textSize.height);
        } else {
            if (axisItem.queueLocation == QueueLocationHead) {
                // 最下面一个下坐标对其线的位置
                frame.origin.y -= textSize.height;
            } else if (axisItem.queueLocation == QueueLocationTrail) {
                // 最上面一个上坐标对其线的位置
            } else {
                frame.origin.y -= textSize.height / 2; // 中间的跟线居中对齐
                axisItem.dashLengths = @[@1.0, @1.0];
            }
        }
        axisItem.textFrame = frame;
        if (self.rightAxis.enable) {
            textSize = [axisItem.extText sizeWithAttributes:@{NSFontAttributeName : axisItem.extTextFont}];
            axisItem.extTextFrame = CGRectMake(rect.size.width-textSize.width, frame.origin.y, frame.size.width, frame.size.height);
        }
        CGLine line;
        line = CGLineMake(self.pointRect.origin.x, y, CGRectGetMaxX(self.pointRect), y);
        if (index == 0 || index == axisCount-1 || self.leftAxis.showGrid) {
            axisItem.line = line;
            axisItem.lineColor = self.leftAxis.lineColor?:axisItem.lineColor;
        }
        
    }
    return xAxisDrawingData;
}

- (NSArray <HACAxisComponents *>*)yAxisDatasInRect:(CGRect)rect {
    NSInteger axisCount = self.yAxisCount;
    if (axisCount <= 0)
        return nil;
    
    NSMutableArray *yAxisDrawingData = [NSMutableArray array];
    for (int index = 0; index < axisCount; index++) {
        HACAxisComponents *axisItem = [[HACAxisComponents alloc] init];
        axisItem.index = index;
        axisItem.axisType = DrawingAxisTypeY;
        axisItem.queueLocation = CGQueueLocation(index, axisCount);
        CGFloat x = [self calculatorXForValue:index min:0 max:axisCount - 1 inRect:self.pointRect];
        CGLine line = CGLineMake(x, CGRectGetMinY(self.pointRect), x, CGRectGetMaxY(self.pointRect));
        axisItem.line = line;
        [yAxisDrawingData addObject:axisItem];
        
        // 计算坐标值，默认在最下面的x轴下面
        axisItem.text = [self stringForAxisTextItem:axisItem];
        if (!axisItem.text) {
            // 如果没有返回使用默认值
            axisItem.text = @"";
        }
        CGSize textSize = [axisItem.text sizeWithAttributes:@{NSFontAttributeName : axisItem.textFont}];
        CGRect frame = CGRectMake(x, CGRectGetMaxY(self.pointRect), textSize.width, textSize.height);
        if (axisItem.queueLocation == QueueLocationHead) {
            // 最左边一个左坐标对其线的位置
        } else if (axisItem.queueLocation == QueueLocationTrail) {
            // 最右面一个右坐标对其线的位置
            frame.origin.x -= textSize.width;
        } else {
            frame.origin.x -= textSize.width / 2; // 中间的跟线居中对齐
            axisItem.dashLengths = @[@1.0, @1.0];
        }
        axisItem.textFrame = frame;
    }
    return yAxisDrawingData;
}

- (CGFloat)calculatorXForValue:(CGFloat)value min:(CGFloat)min max:(CGFloat)max inRect:(CGRect)rect {
    if (value == kDrawingInvaildValue)
        return value;
    
    CGFloat relative = .0;
    if (min != max && value >= min && value <= max) {
        relative = ((value - min) / (max - min)) * CGRectGetWidth(rect);
    }
    else if (value > max) {
        // 超出右边边界做最大值处理
        relative = CGRectGetWidth(rect);
    }
    return CGRectGetMinX(rect) + relative;
}

- (CGFloat)calculatorYForValue:(CGFloat)value min:(CGFloat)min max:(CGFloat)max inRect:(CGRect)rect {
    if (value == kDrawingInvaildValue)
        return value;
    
    CGFloat relative = .0;
    if (min != max && value >= min && value <= max) {
        relative = ((max - value) / (max - min)) * CGRectGetHeight(rect);
    }
    else if (value < min) {
        // 超出下边边界做最小值处理
        relative = CGRectGetHeight(rect);
    }
    return CGRectGetMinY(rect) + relative;
}

- (CGFloat)xPointForIndex:(NSInteger)index inRect:(CGRect)rect {
    // TODO
    //    CGFloat x = [self calculatorXForValue:ABS(index - self.startIndex) min:0 max:self.visualCount inRect:rect];
    CGFloat x = index * self.singleWidth + CGRectGetMinX(rect);
    //    NSLog(@"x = %f,rect = %@",x, NSStringFromCGRect(rect));
    return x;
}

- (DrawingValueType)calculatorValueType:(id)currentData lastData:(id)lastData {
    return DrawingUpValue;
}

- (UIColor *)colorWithValueType:(DrawingValueType)valueType {
    UIColor *color = [UIColor blackColor];
    switch (valueType) {
        case DrawingUpValue:
            color = RGB_HEX(0xFF3E30);
            break;
        case DrawingDownValue:
            color = RGB_HEX(0x17A758);
            break;
        default:
            break;
    }
    return color;
}

- (NSString *)stringForAxisTextItem:(HACAxisComponents *)axisItem {
    return nil;
}

//偏移
- (NSInteger)relativeIdxFromIndex:(NSInteger)i {
    NSInteger idx = i - self.startIndex;
    NSInteger showCount = self.endIndex-self.startIndex+1;
    if (self.startIndex==0
        && showCount<self.visualCount) {
        //滑到最左端，已无历史数据时，显示最前端数据
        idx = self.visualCount-showCount+i;
    }
    return idx;
}

#pragma mark -- api
- (NSUInteger)indexAtChartForCoordinate:(CGPoint)point {
    return 0;
}

- (CGPoint)pointAtChartForIndex:(NSUInteger)index {
    return CGPointZero;
}

- (HACChartDataEntry*)dataAtChartForCoordinate:(CGPoint)point {
    return nil;
}

- (HACChartDataEntry*)dataAtChartForIndex:(NSUInteger)index {
    return nil;
}

#pragma mark - HACAnimatorDelegate
- (void)animatorUpdated:(HACAnimator *)animator {
    [self setNeedsDisplay];
}

- (void)animatorStopped:(HACAnimator *)animator {
    [self setNeedsDisplay];
}
@end
